package tool.expand;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Expander {
	public static String expand(String source, Map<String, Object> map) {
		Pattern p = Pattern.compile("\\$\\{[a-zA-Z][0-9a-zA-Z]*\\}");
		Matcher m = p.matcher(source);
		StringBuilder sb = new StringBuilder();
		int pos = 0;
		while (m.find()) {
			sb.append(source.substring(pos, m.start()));
			String key = source.substring(m.start()+2, m.end()-1);
			Object value = map.get(key);
			sb.append(value);
			pos = m.end();
		}
		sb.append(source.substring(pos));
		return sb.toString();
	}
	
	public static void main(String[] args) {
		String[] tab = { "ko${abba}XXX${koko}YYY" };
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("abba", "ABBA");
		map.put("koko", "KOKO");
		
		for (String s : tab) {
			System.out.printf("%s : %s%n", s, expand(s, map));
		}
	}
	
	
}
